package dj.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;

import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;
import dj.entity.AppCategory;
import dj.entity.AppInfo;
import dj.entity.AppVersion;
import dj.entity.DataDictionary;
import dj.entity.DevUser;
import dj.service.AppInfoService;


@Controller
@RequestMapping("/dev/flatform/app")
public class AppController {
	@Resource
	private AppInfoService service;
	
	@RequestMapping(value="/list")
	public String getAppInfoList(Model model,HttpSession session,String querySoftwareName,String queryFlatformId,
			String queryStatus,
				String queryCategoryLevel1,String queryCategoryLevel2,String queryCategoryLevel3,String pageIndex){
		DevUser devUser=(DevUser) session.getAttribute(Constants.DEV_USER_SESSION);
		Map<String,Object> map=new HashMap<String, Object>();
		List<DataDictionary> flatFormList=null;
		List<DataDictionary> statusList = null;
		List<AppCategory> categoryLevel1List = null;//列出一级分类列表，注：二级和三级分类列表通过异步ajax获取
		List<AppCategory> categoryLevel2List = null;
		List<AppCategory> categoryLevel3List = null;
		map.put("devId", devUser.getId());
		map.put("querySoftwareName", querySoftwareName);
		if(queryStatus!=null&&!queryStatus.equals("")){
			map.put("queryStatus", Integer.valueOf(queryStatus));
		}
		if(queryFlatformId!=null&&!queryFlatformId.equals("")){
		map.put("queryFlatformId", Integer.valueOf(queryFlatformId));
		}
		if(queryCategoryLevel1!=null&&!queryCategoryLevel1.equals("")){
		map.put("queryCategoryLevel1", Integer.valueOf(queryCategoryLevel1));
		}
		if(queryCategoryLevel2!=null&&!queryCategoryLevel2.equals("")){
		map.put("queryCategoryLevel2", Integer.valueOf(queryCategoryLevel2));
		}
		if(queryCategoryLevel3!=null&&!queryCategoryLevel3.equals("")){
		map.put("queryCategoryLevel3", Integer.valueOf(queryCategoryLevel3));
		}
		Integer totalCount=service.selectAll(map);
		PageSupport pageSupport=new PageSupport();
		pageSupport.setTotalCount(totalCount);
		Integer pageNo=null;
		if(pageIndex!=null){
			pageNo=Integer.valueOf(pageIndex);
		}else{
			pageNo=1;
		}
		if(pageNo>pageSupport.getTotalPageCount()){
			pageSupport.setCurrentPageNo(pageSupport.getTotalPageCount());
		}
		if(pageNo<1){
			pageSupport.setCurrentPageNo(1);
		}else{
			pageSupport.setCurrentPageNo(pageNo);
		}
		flatFormList=getDataDictionaryList();
		statusList=getDataDictionaryStatus();
		categoryLevel1List=getCategoryList(null);
		map.put("pageIndex",(pageSupport.getCurrentPageNo()-1)*pageSupport.getPageSize());
		map.put("pageSize", pageSupport.getPageSize());
		List<AppInfo> appInfoList=service.selectPage(map);
		model.addAttribute("appInfoList", appInfoList);
		model.addAttribute("pages", pageSupport);
		model.addAttribute("flatFormList", flatFormList);
		model.addAttribute("statusList", statusList);
		model.addAttribute("categoryLevel1List", categoryLevel1List);
		model.addAttribute("appInfoList", appInfoList);
		model.addAttribute("querySoftwareName", querySoftwareName);
		model.addAttribute("queryFlatformId", queryFlatformId);
		model.addAttribute("queryCategoryLevel1", queryCategoryLevel1);
		model.addAttribute("queryCategoryLevel2", queryCategoryLevel2);
		model.addAttribute("queryCategoryLevel3", queryCategoryLevel3);
		if(queryCategoryLevel2!=null&&!queryCategoryLevel2.equals("")){
			categoryLevel2List=getCategoryList(Integer.valueOf(queryCategoryLevel2));
			model.addAttribute("categoryLevel2List", categoryLevel2List);
		}
		if(queryCategoryLevel3!=null&&!queryCategoryLevel3.equals("")){
			categoryLevel3List=getCategoryList(Integer.valueOf(queryCategoryLevel3));
			model.addAttribute("categoryLevel3List", categoryLevel3List);
		}
		return "developer/appinfolist";
	} 
	
	@RequestMapping("appinfoadd")
	public String appinfoadd(){
		return "developer/appinfoadd";
	}
	
	@RequestMapping("datadictionarylist.json")
	@ResponseBody
	public List<DataDictionary> datadictionarylist(){
		return getDataDictionaryList();
	}
	
	public List<DataDictionary> getDataDictionaryList(){
		return service.getDataDictionaryList();
	}
	
	public List<DataDictionary> getDataDictionaryStatus(){
		return service.getDataDictionaryStatus();
	}
	
	public List<AppCategory> getCategoryList(Integer parentId){
		return service.getCategoryList(parentId);
	}
	
	@RequestMapping(value="/categorylevellist.json",method=RequestMethod.GET)
	@ResponseBody
	public List<AppCategory> getAppCategoryList (@RequestParam String pid){
		Integer parentId=null;
		if(pid!=null&&!pid.equals("")){
			parentId=Integer.parseInt(pid);
		}
		List<AppCategory> list=getCategoryList(parentId);
		 
		 return list;
	}
	
	@RequestMapping(value="/getcategroylevel.json",method=RequestMethod.GET)
	@ResponseBody
	public List<AppCategory> getAppCategory (){
		return getCategoryList(null);
	}
	
	@RequestMapping(value="/checkCode.json",method=RequestMethod.GET)
	@ResponseBody
	public Object checkCode(@RequestParam String APKName){
		Map<String,Object> map=new HashMap<String, Object>();
		if(StringUtils.isNullOrEmpty(APKName)){
			map.put("APKName", "empty");
		}else{
			AppInfo appInfo=service.getAppInfoIdName(null,null, APKName);
			if(appInfo!=null){
				map.put("APKName", "exist");
			}else{
				map.put("APKName", "noexist");
			}
		}
		return JSONObject.toJSONString(map);
	}
	
	@RequestMapping(value="/softwareName.json",method=RequestMethod.GET)
	@ResponseBody
	public Object softwareName(@RequestParam String softwareName){
		Map<String,Object> map=new HashMap<String, Object>();
		if(StringUtils.isNullOrEmpty(softwareName)){
			map.put("softwareName", "empty");
		}else{
			AppInfo appInfo=service.getAppInfoIdName(null,softwareName, null);
			if(appInfo!=null){
				map.put("softwareName", "exist");
			}else{
				map.put("softwareName", "noexist");
			}
		}
		return JSONObject.toJSONString(map);
	}
	
	@RequestMapping(value="/appinfoaddsave",method=RequestMethod.POST)
	public String addSave(AppInfo appInfo,HttpSession session,HttpServletRequest request,
					@RequestParam(value="a_logoPicPath",required= false) MultipartFile attach){	
		String logoPicPath=null;
		String logoLocPath=null;
		if(!attach.isEmpty()){
			String path=request.getServletContext().getRealPath("statics"+java.io.File.separator+"uploadfiles");
			String oldFileName=attach.getOriginalFilename();
			String prefix=FilenameUtils.getExtension(oldFileName);
			int filesize = 500000;
			if(attach.getSize()>filesize){
				request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_4);
				return "developer/appinfoadd";
			}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") 
					   ||prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")){
				String newFileName=appInfo.getAPKName()+".jpg";
				File newFile=new File(path, newFileName);
				if(!newFile.exists()){
					newFile.mkdirs();
				}
				try {
					attach.transferTo(newFile);
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					e.printStackTrace();
					request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_2);
					return "developer/appinfoadd";
				}
				logoPicPath = request.getContextPath()+"/statics/uploadfiles/"+newFileName;
				logoLocPath = newFileName;
			}else{
				request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_3);
				return "developer/appinfoadd";
			}
		}
		DevUser DevUser=(DevUser) session.getAttribute(Constants.DEV_USER_SESSION);
		appInfo.setCreatedBy(DevUser.getId());
		appInfo.setDevId(DevUser.getId());
		appInfo.setCreationDate(new Date());
		appInfo.setLogoLocPath(logoLocPath);
		appInfo.setLogoPicPath(logoPicPath);
		appInfo.setStatus(Long.valueOf("1"));
		if(service.insert(appInfo)){
			return "redirect:/dev/flatform/app/list";
		}
		
		return "developer/appinfoadd";
	}
	
	@RequestMapping("appinfomodify")
	public String appinfomodify(@RequestParam String id,Model model){
		AppInfo appInfo=service.getAppInfoIdName(Integer.parseInt(id),null, null);
		model.addAttribute("appInfo", appInfo);
		return "developer/appinfomodify";
	}
	
	@RequestMapping(value="appinfomodifysave",method=RequestMethod.POST)
	public String appinfomodifysave(AppInfo appInfo,HttpSession session,HttpServletRequest request,
			@RequestParam(value="attach",required= false) MultipartFile attach){
		String logoPicPath=null;
		String logoLocPath=null;
		if(!attach.isEmpty()){
			String path=request.getServletContext().getRealPath("statics"+java.io.File.separator+"uploadfiles");
			String oldFileName=attach.getOriginalFilename();
			String prefix=FilenameUtils.getExtension(oldFileName);
			int filesize = 500000;
			if(attach.getSize()>filesize){
				request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_4);
				return "redirect:/dev/flatform/ap/appinfomodify";
			}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") 
					   ||prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")){
				String newFileName=appInfo.getAPKName()+".jpg";
				File newFile=new File(path, newFileName);
				if(!newFile.exists()){
					newFile.mkdirs();
				}
				try {
					attach.transferTo(newFile);
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					e.printStackTrace();
					request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_2);
					return "redirect:/dev/flatform/ap/appinfomodify";
				}
				logoPicPath = request.getContextPath()+"/statics/uploadfiles/"+newFileName;
				logoLocPath = newFileName;
				appInfo.setLogoLocPath(logoLocPath);
				appInfo.setLogoPicPath(logoPicPath);
			}else{
				request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_3);
				return "redirect:/dev/flatform/ap/appinfomodify";
			}
		}
		DevUser DevUser=(DevUser) session.getAttribute(Constants.DEV_USER_SESSION);
		appInfo.setModifyBy(DevUser.getId());
		appInfo.setModifyDate(new Date());
		
		if(service.updateAppInfo(appInfo)){
			return "redirect:/dev/flatform/app/list";
		}
		
		return "redirect:/dev/flatform/ap/appinfomodify";
	}
	
	@RequestMapping(value="/delfile",method=RequestMethod.GET)
	@ResponseBody
	public Object delFile(@RequestParam(value="flag",required=false) String flag,
			@RequestParam(value="id",required=false) String id,HttpServletRequest request){
		Map<String,Object> map=new HashMap<String, Object>();
		
		String fileLocPath="";
		if(flag == null || flag.equals("") ||
				id == null || id.equals("")){
				map.put("result", "failed");
			}else if(flag.equals("logo")){
				String path=request.getServletContext().getRealPath("statics"+java.io.File.separator+"uploadfiles");
				fileLocPath=path+java.io.File.separator+service.getAppInfoIdName(Integer.parseInt(id),null, null).getLogoLocPath();
				File file = new File(fileLocPath);
				if(file.exists()){
					if(file.delete()){
						if(service.updatelogo(Integer.parseInt(id))){
							map.put("result", "success");
						}
					}
				}
			}else if(flag.equals("apk")){//删除apk文件（操作app_version）
				String path=request.getServletContext().getRealPath("statics"+java.io.File.separator+"uploadfiles");
				fileLocPath=path+java.io.File.separator+service.getAppVersion(Integer.parseInt(id)).getApkFileName();
				File file = new File(fileLocPath);
				if(file.exists()){
					if(file.delete()){
						if(service.updateApk(Integer.parseInt(id))){
							map.put("result", "success");
						}
					}
				}
			}
			return JSONArray.toJSONString(map);
	}
	
	@RequestMapping("addversion")
	public String addversion(String id,String error,Model model){
		List<AppVersion> appVersionList=service.AppVersionApp(Integer.parseInt(id));
		if(error!=null){
		if(error.equals("error1")){
			model.addAttribute("fileUploadError",Constants.FILEUPLOAD_ERROR_4);
		}
		if(error.equals("error2")){
			model.addAttribute("fileUploadError",Constants.FILEUPLOAD_ERROR_3);
		}
		if(error.equals("error3")){
			model.addAttribute("fileUploadError",Constants.FILEUPLOAD_ERROR_2);
		}
		if(error.equals("error4")){
			model.addAttribute("fileUploadError","保存失败");
		}
		}
		model.addAttribute("appVersionList", appVersionList);
		model.addAttribute("id", id);
		return "developer/appversionadd";
	}
	
	@RequestMapping(value="/addversionsave",method=RequestMethod.POST)
	public String addversionsave(AppVersion appVersion,@RequestParam(value="a_downloadLink",required=false)MultipartFile multipartFile,
				HttpServletRequest request,HttpSession session){
		String apkLocPath=null;
		String downloadLink=null;
		String apkFileName=null;
		if(!multipartFile.isEmpty()){
			String path=request.getServletContext().getRealPath("statics"+java.io.File.separator+"uploadfiles");
			String oldFileName=multipartFile.getOriginalFilename();
			String prefix=FilenameUtils.getExtension(oldFileName);
			int fileSize=1024*1024*500;
			if(multipartFile.getSize()>fileSize){
				return "redirect:/dev/flatform/app/addversion?id="+appVersion.getAppId()+"&error=error1";
			}
			if(prefix.equals("apk")){
				String a=String.valueOf(appVersion.getAppId());
				String newfileName=service.getAppInfoIdName(Integer.parseInt(a), null, null).getAPKName()+".apk";
				File file=new File(path+File.separator+newfileName);
				if(!file.exists()){
					file.mkdirs();
				}
				try {
					multipartFile.transferTo(file);
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				downloadLink=request.getContextPath()+"/statics/uploadfiles/"+newfileName;
				apkLocPath=path+File.separator+newfileName;
				apkFileName=newfileName;
			}else{
				return "redirect:/dev/flatform/app/addversion?id='"+appVersion.getAppId()+"'&error=error2";
			}
		}else{
			return "redirect:/dev/flatform/app/addversion?id='"+appVersion.getAppId()+"'&error=error3";
		}
		appVersion.setDownloadLink(downloadLink);
		appVersion.setApkLocPath(apkLocPath);
		appVersion.setApkFileName(apkFileName);
		DevUser DevUser=(DevUser) session.getAttribute(Constants.DEV_USER_SESSION);
		appVersion.setCreatedBy(DevUser.getId());
		appVersion.setCreationDate(new Date());
		if(service.insertAppVersion(appVersion)){
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("id",appVersion.getAppId());
			map.put("versionId", appVersion.getId());
			if(service.updateAppVersionId(map)){
				return "redirect:/dev/flatform/app/list";
			}
		}
		return "redirect:/dev/flatform/app/addversion?id='"+appVersion.getAppId()+"'&error=error4";
	}
	
	@RequestMapping("appversionmodify")
	public String appversionmodify(String aid,String vid,String error,Model model){
		List<AppVersion> appVersionList=service.AppVersionApp(Integer.parseInt(aid));
		AppVersion appVersion=service.getAppVersion(Integer.parseInt(vid));
		if(error!=null){
			if(error.equals("error1")){
				model.addAttribute("fileUploadError",Constants.FILEUPLOAD_ERROR_4);
			}
			if(error.equals("error2")){
				model.addAttribute("fileUploadError",Constants.FILEUPLOAD_ERROR_3);
			}
			if(error.equals("error3")){
				model.addAttribute("fileUploadError",Constants.FILEUPLOAD_ERROR_2);
			}
			if(error.equals("error4")){
				model.addAttribute("fileUploadError","修改失败");
			}
			
		}
		model.addAttribute("appVersionList", appVersionList);
		model.addAttribute("id", aid);
		model.addAttribute("appVersion", appVersion);
		return "developer/appversionmodify";
		
	}
	
	@RequestMapping("appversionmodifysave")
	public String appversionmodifysave(AppVersion appVersion,@RequestParam(value="attach",required=false)MultipartFile multipartFile,
			HttpServletRequest request,HttpSession session){
		String apkLocPath=null;
		String downloadLink=null;
		String apkFileName=null;
		if(!multipartFile.isEmpty()){
			String path=request.getServletContext().getRealPath("statics"+java.io.File.separator+"uploadfiles");
			String oldFileName=multipartFile.getOriginalFilename();
			String prefix=FilenameUtils.getExtension(oldFileName);
			int fileSize=1024*1024*500;
			if(multipartFile.getSize()>fileSize){
				return "redirect:/dev/flatform/app/appversionmodify?aid="+appVersion.getAppId()+"&error=error1&vid="+appVersion.getId();
			}
			if(prefix.equals("apk")){
				String a=String.valueOf(appVersion.getAppId());
				String newfileName=service.getAppInfoIdName(Integer.parseInt(a), null, null).getAPKName()+".apk";
				File file=new File(path+File.separator+newfileName);
				if(!file.exists()){
					file.mkdirs();
				}
				try {
					multipartFile.transferTo(file);
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				downloadLink=request.getContextPath()+"/statics/uploadfiles/"+newfileName;
				apkLocPath=path+File.separator+newfileName;
				apkFileName=newfileName;
				appVersion.setDownloadLink(downloadLink);
				appVersion.setApkLocPath(apkLocPath);
				appVersion.setApkFileName(apkFileName);
			}else{
				return "redirect:/dev/flatform/app/appversionmodify?aid="+appVersion.getAppId()+"&error=error2&vid="+appVersion.getId()+"";
			}
		}
		
		DevUser DevUser=(DevUser) session.getAttribute(Constants.DEV_USER_SESSION);
		appVersion.setModifyBy(DevUser.getId());
		appVersion.setModifyDate(new Date());
		if(service.updateAppVersion(appVersion)){
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("id",appVersion.getAppId());
			map.put("versionId", appVersion.getId());
			if(service.updateAppVersionId(map)){
				return "redirect:/dev/flatform/app/list";
			}
		}
		return "redirect:/dev/flatform/app/appversionmodify?aid='"+appVersion.getAppId()+"'&error=error4&vid='"+appVersion.getId()+"'";
	}
	
	@RequestMapping("appview/{id}")
	public String appview(@PathVariable String id,Model model){
		AppInfo appInfo=service.getAppInfo(Integer.parseInt(id));
		List<AppVersion> appVersionList=service.AppVersionApp(Integer.parseInt(id));
		model.addAttribute("appInfo", appInfo);
		model.addAttribute("appVersionList", appVersionList);
		return "developer/appinfoview";
	}
	
	@RequestMapping("delapp.json")
	@ResponseBody
	public Object delapp(String id){
		Map<String,Object> map=new HashMap<String, Object>();
		AppInfo appInfo=service.getAppInfo(Integer.parseInt(id));
		if(appInfo!=null){
		if(service.delAppInfo(Integer.parseInt(id))){
			map.put("delResult", "true");
		}else{
			map.put("delResult", "false");
		}
		}else{
			map.put("delResult", "notexist");
		}
		return  JSONObject.toJSONString(map);
	}
	
	@RequestMapping(value="/{appId}/sale")
	@ResponseBody
	public Object sale(@PathVariable String appId,HttpSession session){
		Map<String,Object> map=new HashMap<String, Object>();
		if(appId!=null&&appId!=""){
			map.put("errorCode", "0");
			DevUser devUser=(DevUser) session.getAttribute(Constants.DEV_USER_SESSION);
			if(service.updateAppStatus(Integer.parseInt(appId), devUser.getId())){
				map.put("resultMsg", "success");
			}else{
				map.put("resultMsg", "failed");
			}
		}else{
			map.put("errorCode", "exception000001");
		}
		return map;
	}
}
